<template>
    <div class="cart-container">
        <div class="cart-content-wrap">
            <h1 class="cart-title">购物车</h1>
            <div class="cart-count">{{ totalItems }}件商品</div>

            <div v-if="cartItems.length">
                <div class="select-all-row">
                    <label class="modern-checkbox">
                        <input type="checkbox" v-model="selectAll" @change="handleSelectAllChange">
                        <span class="checkmark"></span>
                        <span class="checkbox-label">全选</span>
                    </label>
                </div>

                <div class="cart-seller-group" v-for="(group, seller) in groupedItems" :key="seller">
                    <div class="seller-header">
                        <div class="seller-avatar">{{ seller.charAt(0) }}</div>
                        <h3>{{ seller }}的商品</h3>
                    </div>

                    <div class="seller-items">
                        <TransitionGroup name="item-fade">
                        <div class="cart-item" v-for="(item, index) in group" :key="item.id">
                            <div class="cart-item-content">
                                <label class="modern-checkbox">
                                    <input type="checkbox" v-model="item.selected" @change="handleItemCheckboxChange">
                                    <span class="checkmark"></span>
                                </label>
                                
                                <div class="product-info">
                                    <div class="product-image-wrapper">
                                        <el-image :src="item.image" :preview-src-list="[item.image]" fit="cover" class="product-image" />
                                    </div>
                                    <div class="product-details">
                                        <h3 class="product-name">{{ item.name }}</h3>
                                        <p class="product-desc">{{ item.description || '暂无商品描述' }}</p>
                                        <div class="product-location-info">
                                            <div class="school-badge" v-if="item.schoolName || (item.location && item.location.includes('大学'))">
                                                <i class="el-icon-school"></i>
                                                <span>{{ item.schoolName || (item.location && item.location.includes('大学') ? item.location.split('-')[0].trim() : '未知学校') }}</span>
                                            </div>
                                        <p class="location">
                                            <i class="el-icon-location"></i>
                                            {{ item.location || '未知位置' }}
                                            <button class="view-location-btn" @click="viewLocation(item)">
                                                查看位置
                                            </button>
                                        </p>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="product-right">
                                    <div class="product-price">
                                        ¥{{ item.price }}
                                    </div>
                                </div>
                            </div>
                            <div class="item-actions">
                                <button class="delete-btn" @click="removeFromCart(item)">
                                    <i class="el-icon-delete"></i>
                                    <span>删除</span>
                                </button>
                            </div>
                            
                            <div class="item-divider" v-if="index < group.length - 1"></div>
                        </div>
                        </TransitionGroup>
                    </div>
                    <div class="seller-divider"></div>
                </div>

                <div class="cart-footer">
                    <div class="footer-left">
                        <label class="modern-checkbox">
                            <input type="checkbox" v-model="selectAll" @change="handleSelectAllChange">
                            <span class="checkmark"></span>
                            <span class="checkbox-label">全选</span>
                        </label>
                        <button class="text-btn" @click="clearCart">清空购物车</button>
                    </div>
                    <div class="footer-right">
                        <div class="total">
                            总计: <span class="total-price">¥{{ selectedTotalPrice }}</span>
                        </div>
                        <div class="selected-count">已选择 <span>{{ selectedItems.length }}</span> 件商品</div>
                        <button class="checkout-btn" 
                            :class="{'disabled': !selectedItems.length}" 
                            :disabled="!selectedItems.length"
                            @click="checkout">
                            <span class="btn-text">去结算</span>
                            <span class="btn-icon">→</span>
                        </button>
                    </div>
                </div>
            </div>

            <el-empty v-else description="购物车是空的" :image-size="200">
                <el-button type="primary" @click="$router.push('/')">
                    去逛逛
                </el-button>
                <el-button @click="debugCart" type="info" style="margin-top: 10px">
                    调试购物车
                </el-button>
                <el-button @click="refreshCart" type="warning" style="margin-top: 10px">
                    强制刷新
                </el-button>
            </el-empty>
        </div>
    </div>

    <!-- 订单创建弹窗 -->
    <OrderCreateDialog
        :visible="orderDialogVisible"
        @update:visible="orderDialogVisible = $event"
        :product-info="selectedProduct"
        @order-created="handleOrderCreated"
    />
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'
import { getCartItems, removeFromCart as apiRemoveFromCart, clearCart as apiClearCart } from '../../api/cart'
import type { CartItem as ApiCartItem } from '../../api/cart'
import OrderCreateDialog from '@/components/order/OrderCreateDialog.vue'

// 请求缓存控制
let lastCartRequestTime = 0
const REQUEST_CACHE_TIMEOUT = 500 // 毫秒
let pendingCartRequest = null

interface ApiResponse<T> {
  code: number;
  data: T;
  message: string;
}

interface CartItemUI {
  id: number;
  productId?: number;
  name: string;
  price: number;
  quantity: number;
  selected: boolean;
  image: string;
  location: string;
  schoolName?: string;
  description: string;
  seller: {
    id: number;
    name: string;
    avatar: string;
  }
}

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)

// 购物车数据
const cartItems = ref<CartItemUI[]>([])

// 处理后端返回的数据，确保即使有null值也能正确显示
function processApiData(apiData: any) {
  // 确保所有可能为null的字段都有默认值
  return {
    id: apiData.id || 0,
    productId: apiData.productId || 0,
    name: apiData.productName || apiData.name || '未命名商品',
    price: Number(apiData.price) || 0,
    quantity: 1,
    selected: true,
    image: apiData.productImage || apiData.image || '/src/assets/placeholder.png',
    location: apiData.location || '未知位置',
    description: apiData.description || '暂无描述',
    seller: {
      id: apiData.userId || apiData.sellerId || 0,
      name: apiData.userName || apiData.sellerName || '未知卖家',
      avatar: apiData.userAvatar || apiData.sellerAvatar || '/src/assets/avatar.png'
    }
  }
}

// 加载购物车数据
async function fetchCartItems() {
  try {
    loading.value = true
    const userId = userStore.userInfo?.id
    if (!userId) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }
    
    // 添加请求缓存控制，避免短时间内重复请求
    const now = Date.now()
    if (now - lastCartRequestTime < REQUEST_CACHE_TIMEOUT) {
      console.log('购物车请求太频繁，使用缓存或等待上一个请求完成')
      if (pendingCartRequest) {
        await pendingCartRequest
        loading.value = false
        return
      }
      // 如果有缓存数据，则不再请求
      if (cartItems.value.length > 0) {
        loading.value = false
        return
      }
    }
    
    lastCartRequestTime = now
    
    try {
      // 记录请求Promise以便重用
      pendingCartRequest = getCartItems({ userId }) as unknown as Promise<ApiResponse<ApiCartItem[]>>
      const res = await pendingCartRequest
      
      console.log('购物车API返回数据:', res) // 调试日志，查看API返回的具体数据
      
      // 首先检查res是否存在且是否为对象
      if (res && typeof res === 'object') {
        // 尝试定位商品数据
        let productsList = null;
        
        // 尝试提取数据 - 检查常见的数据结构
        if (res.code === 200) {
          if (res.data) {
            // 检查res.data是否为数组
            if (Array.isArray(res.data)) {
              productsList = res.data;
            } 
            // 检查res.data.list是否存在
            else if (res.data.list && Array.isArray(res.data.list)) {
              productsList = res.data.list;
            }
            // 检查res.data.data是否存在
            else if (res.data.data && Array.isArray(res.data.data)) {
              productsList = res.data.data;
            }
            // 处理截图中展示的结构: { code: 200, data: { list: [{ id, userId, productId, productName, ...}] } }
            else if (typeof res.data === 'object') {
              if (res.data.list && Array.isArray(res.data.list)) {
                productsList = res.data.list;
              } else {
                // 单个对象的情况
                productsList = [res.data];
              }
            }
          }
        } else if (Array.isArray(res)) {
          // 直接是数组的情况
          productsList = res;
        }
        
        console.log('提取的商品列表:', productsList);
        
        if (productsList && productsList.length > 0) {
          // 成功提取到商品数据
          cartItems.value = productsList.map((item: any) => {
            // 特别处理截图中看到的格式
            if (item.productId && item.productName) {
              return {
                id: item.id || 0,
                productId: item.productId,
                name: item.productName,
                price: Number(item.price) || 0,
                quantity: 1,
                selected: true,
                image: item.productImage || '/src/assets/placeholder.png',
                location: item.locationDescription || '学校位置',
                schoolName: item.schoolName || '',
                description: item.productDescription || '暂无描述',
                seller: {
                  id: item.userId || 0,
                  name: item.userName || item.sellerName || '未知卖家',
                  avatar: item.sellerAvatar || '/src/assets/avatar.png'
                }
              };
            } else if (item.product) {
              // 包含product对象的格式
              const product = item.product;
              return {
                id: item.id,
                productId: item.productId || product.id,
                name: product.name || '未命名商品',
                price: Number(product.price) || 0,
                quantity: item.quantity || 1,
                selected: true,
                image: product.image || product.mainImageUrl || (product.images && product.images.length > 0 ? product.images[0] : null) || '/src/assets/placeholder.png',
                location: product.location || '学校位置',
                description: product.description || '暂无描述',
                seller: {
                  id: product.userId || product.sellerId || 0,
                  name: product.userName || product.sellerName || '未知卖家',
                  avatar: product.userAvatar || product.sellerAvatar || '/src/assets/avatar.png'
                }
              };
            } else {
              // 其他格式
              return processApiData(item);
            }
          });
          
          console.log('处理后的购物车数据:', cartItems.value);
          return;
        }
        
        // 如果没有找到商品数据
        console.warn('未找到购物车商品数据，使用默认数据');
        useCartMockData();
      } else {
        console.error('API返回格式错误:', res);
        ElMessage.warning('API返回格式错误，使用默认数据');
        useCartMockData();
      }
    } catch (error) {
      console.error('获取购物车列表失败:', error);
      ElMessage.warning('无法连接到服务器，使用默认数据');
      useCartMockData();
    } finally {
      pendingCartRequest = null;
    }
  } finally {
    loading.value = false;
  }
}

// 使用模拟数据
function useCartMockData() {
  cartItems.value = [
    {
        id: 1,
      productId: 101,
        name: 'MacBook Pro',
        price: 5300,
        quantity: 1,
        selected: true,
        image: '/src/assets/placeholder.png',
        location: '北京大学 - 理科教学楼',
        description: '2023年新款，M2芯片，16GB内存，512GB固态硬盘',
        seller: {
            id: 1,
            name: '张伟',
            avatar: '/src/assets/avatar.png'
        }
    },
    {
        id: 2,
      productId: 102,
        name: '中学英语',
        price: 30,
        quantity: 1,
        selected: true,
        image: '/src/assets/placeholder.png',
        location: '北京大学 - 文科教学楼',
        description: '九年级英语教材，全新未使用，送笔记一本',
        seller: {
            id: 1,
            name: '张伟',
            avatar: '/src/assets/avatar.png'
        }
    },
    {
        id: 3,
      productId: 103,
        name: '电吉他',
        price: 500,
        quantity: 1,
        selected: true,
        image: '/src/assets/placeholder.png',
        location: '清华大学 - 艺术中心',
        description: 'Fender品牌，使用不到半年，音色优美，附送琴包',
        seller: {
            id: 2,
            name: '王丽',
            avatar: '/src/assets/avatar.png'
        }
    }
  ]
}

// 组件挂载时加载购物车数据
onMounted(() => {
  fetchCartItems()
})

// 卖家选择状态
const sellerCheckboxes = reactive<Record<string, boolean>>({})

// 全选状态
const selectAll = ref(true)

// 按卖家分组商品
const groupedItems = computed(() => {
    const groups = {}
    cartItems.value.forEach(item => {
        const sellerName = item.seller.name
        if (!groups[sellerName]) {
            groups[sellerName] = []
        }
        groups[sellerName].push(item)
    })
    return groups
})

// 已选择的商品
const selectedItems = computed(() => {
    return cartItems.value.filter(item => item.selected)
})

// 商品总数
const totalItems = computed(() => {
    return cartItems.value.length
})

// 已选商品总价
const selectedTotalPrice = computed(() => {
    return selectedItems.value.reduce((total, item) => {
        return total + (item.price * item.quantity)
    }, 0).toFixed(2)
})

// 初始化卖家选择状态
watch(() => groupedItems.value, (groups) => {
    for (const seller in groups) {
        if (!(seller in sellerCheckboxes)) {
            sellerCheckboxes[seller] = true
        }
    }
}, { immediate: true })

// 处理全选切换
const handleSelectAllChange = (val: boolean) => {
    cartItems.value.forEach(item => {
        item.selected = val
    })
    
    // 更新卖家选择状态
    Object.keys(sellerCheckboxes).forEach(seller => {
        sellerCheckboxes[seller] = val
    })
    
    updateTotalPrice()
}

// 处理卖家选择切换
const handleSellerCheckboxChange = (seller: string, val: boolean) => {
    // 更新该卖家下所有商品的选择状态
    cartItems.value.forEach(item => {
        if (item.seller.name === seller) {
            item.selected = val
        }
    })
    
    // 检查是否全选
    checkSelectAllState()
    updateTotalPrice()
}

// 处理单个商品选择切换
const handleItemCheckboxChange = () => {
    // 更新卖家选择状态
    for (const seller in groupedItems.value) {
        const allSelected = groupedItems.value[seller].every(item => item.selected)
        sellerCheckboxes[seller] = allSelected
    }
    
    // 检查是否全选
    checkSelectAllState()
    updateTotalPrice()
}

// 检查全选状态
const checkSelectAllState = () => {
    selectAll.value = cartItems.value.length > 0 && cartItems.value.every(item => item.selected)
}

// 更新总价
const updateTotalPrice = () => {
    // 总价会通过计算属性自动更新
}

// 查看商品位置
const viewLocation = (item) => {
    ElMessage.info(`正在查看${item.name}的位置信息`)
    // 可以导航到地图页面，或者打开一个地图弹窗
    router.push({
        path: '/map',
        query: { productId: item.id }
    })
}

// 从购物车移除商品
const removeFromCart = (item: CartItemUI) => {
    ElMessageBox.confirm(
        '确定要从购物车中移除该商品吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        const userId = userStore.userInfo?.id
        if (!userId) {
            ElMessage.error('请先登录')
            return
        }
        
        try {
            const res = await apiRemoveFromCart({ userId, cartItemId: item.id }) as ApiResponse<null>
            if (res.code === 200) {
                // 服务器移除成功后处理本地数据
                removeCartItemLocally(item.id)
                ElMessage.success('商品已移除')
            } else {
                // API返回错误，仍然在本地删除
                ElMessage.warning('服务器返回错误，仅在本地移除商品')
                removeCartItemLocally(item.id)
            }
        } catch (error) {
            console.error('移除商品失败:', error)
            // 当API请求失败时，仍然可以在本地移除商品
            ElMessage.warning('无法连接到服务器，仅在本地移除商品')
            removeCartItemLocally(item.id)
        }
    }).catch(() => {})
}

// 本地移除购物车商品
function removeCartItemLocally(itemId: number) {
    cartItems.value = cartItems.value.filter(i => i.id !== itemId)
        
        // 检查卖家组是否为空
        for (const seller in groupedItems.value) {
            if (groupedItems.value[seller].length === 0) {
                delete sellerCheckboxes[seller]
            }
        }
        
        checkSelectAllState()
        updateTotalPrice()
}

// 清空购物车
const clearCart = () => {
    ElMessageBox.confirm(
        '确定要清空购物车吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        const userId = userStore.userInfo?.id
        if (!userId) {
            ElMessage.error('请先登录')
            return
        }
        
        try {
            const res = await apiClearCart({ userId }) as ApiResponse<null>
            if (res.code === 200) {
                // 服务器清空成功后处理本地数据
                clearCartLocally()
                ElMessage.success('购物车已清空')
            } else {
                // API返回错误，仍然在本地清空
                ElMessage.warning('服务器返回错误，仅在本地清空购物车')
                clearCartLocally()
            }
        } catch (error) {
            console.error('清空购物车失败:', error)
            // 当API请求失败时，仍然可以在本地清空购物车
            ElMessage.warning('无法连接到服务器，仅在本地清空购物车')
            clearCartLocally()
        }
    }).catch(() => {})
}

// 本地清空购物车
function clearCartLocally() {
        cartItems.value = []
        Object.keys(sellerCheckboxes).forEach(key => {
            delete sellerCheckboxes[key]
        })
        selectAll.value = false
}

// 订单创建弹窗
const orderDialogVisible = ref(false)
const selectedProduct = ref(null)

// 结算
const checkout = () => {
    console.log('点击去结算按钮');
    
    if (selectedItems.value.length === 0) {
        ElMessage.warning('请至少选择一件商品')
        return
    }
    
    // 先检查登录状态
    const token = localStorage.getItem('token')
    const userInfo = localStorage.getItem('userInfo')
    
    if (!token || !userInfo) {
        console.log('用户未登录，显示登录提示');
        ElMessageBox.confirm(
            '请先登录后再购买',
            '提示',
            {
                confirmButtonText: '去登录',
                cancelButtonText: '取消',
                type: 'warning'
            }
        ).then(() => {
            // 记录当前路径，登录后可以返回
            router.push(`/login?redirect=${encodeURIComponent(router.currentRoute.value.fullPath)}`)
        }).catch(() => {})
        return
    }
    
    // 如果选择了多个商品，提示只能一次购买一件商品
    if (selectedItems.value.length > 1) {
        console.log('选择了多个商品，显示提示');
        ElMessageBox.confirm(
            '目前只支持单件商品结算，请只选择一件商品',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info'
            }
        )
        return
    }
    
    // 设置选中的商品信息
    const selectedItem = selectedItems.value[0];
    if (!selectedItem || !selectedItem.productId) {
        ElMessage.warning('商品信息不完整，无法结算');
        return;
    }
    
    console.log('准备弹出订单创建窗口，商品信息:', {
        id: selectedItem.productId,
        name: selectedItem.name,
        price: selectedItem.price
    });
    
    selectedProduct.value = {
        id: selectedItem.productId,
        name: selectedItem.name,
        price: selectedItem.price,
        images: [selectedItem.image]
    }
    
    // 显示订单创建弹窗
    orderDialogVisible.value = true;
    console.log('订单弹窗可见性:', orderDialogVisible.value);
}

// 处理订单创建完成
const handleOrderCreated = (order) => {
    ElMessage.success('订单创建成功!')
    
    // 从购物车移除已购买的商品
    const productId = selectedProduct.value.id
    const itemToRemove = cartItems.value.find(item => item.productId === productId)
    
    if (itemToRemove) {
        removeFromCart(itemToRemove)
    }
    
    // 跳转到用户中心的订单列表
    router.push('/user/center?menu=orders')
}

// 加强版调试功能
const debugCart = () => {
  try {
    const userId = userStore.userInfo?.id
    if (!userId) {
      ElMessage.error('请先登录')
      return
    }
    
    // 先尝试从localStorage中获取原始响应
    const cachedResponse = localStorage.getItem('cartApiResponse')
    if (cachedResponse) {
      console.log('缓存的购物车API响应:', JSON.parse(cachedResponse))
      ElMessage.info('请检查控制台查看调试信息')
    } else {
      ElMessage.warning('没有缓存的购物车响应')
    }
    
    // 显示当前处理后的购物车数据
    console.log('当前处理后的购物车数据:', cartItems.value)
    
    // 强制触发一次API请求并缓存原始响应
    getCartItems({ userId }).then(res => {
      console.log('实时购物车API响应:', res)
      
      // 缓存原始响应以供调试
      localStorage.setItem('cartApiResponse', JSON.stringify(res))
      
      // 打印响应结构
      console.log('响应结构分析:')
      if (res && typeof res === 'object') {
        console.log('- 响应根级属性:', Object.keys(res))
        
        if (res.data) {
          console.log('- data属性类型:', typeof res.data)
          console.log('- data属性内容:', res.data)
          
          if (typeof res.data === 'object' && !Array.isArray(res.data)) {
            console.log('- data下级属性:', Object.keys(res.data))
            
            if (res.data.list) {
              console.log('- data.list类型:', typeof res.data.list)
              console.log('- data.list长度:', Array.isArray(res.data.list) ? res.data.list.length : '非数组')
              
              if (Array.isArray(res.data.list) && res.data.list.length > 0) {
                console.log('- data.list第一项结构:', Object.keys(res.data.list[0]))
              }
            }
          }
        }
      }
      
      ElMessage.success('已在控制台打印调试信息')
    }).catch(err => {
      console.error('调试时API请求失败:', err)
      ElMessage.error('调试时API请求失败')
    })
  } catch (e) {
    console.error('调试过程出错:', e)
    ElMessage.error('调试过程出错')
  }
}

// 强制刷新购物车
const refreshCart = () => {
  // 清空本地缓存
  cartItems.value = []
  pendingCartRequest = null
  lastCartRequestTime = 0
  
  // 强制重新加载
  ElMessage.info('正在强制刷新购物车...')
  fetchCartItems()
}
</script>

<style scoped>
.cart-container {
    width: 100%;
    margin: 0 auto;
    padding: 0;
    background-color: #f5f5f5;
    min-height: calc(100vh - 64px);
}

.cart-content-wrap {
    max-width: 1000px;
    margin: 0 auto;
    padding: 24px 16px;
    background-color: #fff;
    box-shadow: 0 1px 6px rgba(0, 0, 0, 0.03);
    border-radius: 8px;
}

.cart-title {
    font-size: 28px;
    font-weight: bold;
    color: #333;
    margin-bottom: 4px;
    margin-top: 0;
}

.cart-count {
    font-size: 14px;
    color: #666;
    margin-bottom: 20px;
}

/* 现代化复选框 */
.modern-checkbox {
    display: inline-flex;
    align-items: center;
    position: relative;
    cursor: pointer;
    font-size: 14px;
    user-select: none;
}

.modern-checkbox input {
    position: absolute;
    opacity: 0;
    cursor: pointer;
    height: 0;
    width: 0;
}

.checkmark {
    position: relative;
    height: 20px;
    width: 20px;
    background-color: #fff;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    transition: all 0.3s;
}

.modern-checkbox:hover input ~ .checkmark {
    border-color: #4080ff;
}

.modern-checkbox input:checked ~ .checkmark {
    background-color: #4080ff;
    border-color: #4080ff;
}

.checkmark:after {
    content: "";
    position: absolute;
    display: none;
    left: 7px;
    top: 3px;
    width: 4px;
    height: 8px;
    border: solid white;
    border-width: 0 2px 2px 0;
    transform: rotate(45deg);
}

.modern-checkbox input:checked ~ .checkmark:after {
    display: block;
    animation: checkmark-appear 0.2s ease-in-out;
}

@keyframes checkmark-appear {
    0% { opacity: 0; transform: rotate(45deg) scale(0.5); }
    100% { opacity: 1; transform: rotate(45deg) scale(1); }
}

.checkbox-label {
    margin-left: 8px;
    color: #333;
}

.select-all-row {
    padding: 12px 0;
    font-size: 14px;
    border-bottom: 2px solid #f0f0f0;
    margin-bottom: 12px;
}

.cart-seller-group {
    margin-bottom: 24px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    overflow: hidden;
}

.seller-header {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin: 0;
    padding: 16px;
    background-color: #f9f9f9;
    display: flex;
    align-items: center;
    gap: 12px;
    border-bottom: 1px solid #eaeaea;
}

.seller-avatar {
    width: 32px;
    height: 32px;
    background-color: #4080ff;
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
}

.seller-header h3 {
    margin: 0;
}

.seller-items {
    padding: 0;
}

.cart-item {
    padding: 16px;
    transition: all 0.3s;
    position: relative;
}

.cart-item:hover {
    background-color: #f9f9f9;
}

.cart-item-content {
    display: flex;
    align-items: center;
    gap: 16px;
}

.product-info {
    display: flex;
    align-items: center;
    gap: 16px;
    flex: 1;
}

.product-image-wrapper {
    width: 120px;
    height: 120px;
    background-color: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.cart-item:hover .product-image-wrapper {
    transform: translateY(-3px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.product-image {
    width: 100px;
    height: 100px;
    object-fit: contain;
    transition: all 0.3s;
}

.product-details {
    flex: 1;
    min-width: 0;
}

.product-name {
    margin: 0 0 8px 0;
    font-size: 16px;
    font-weight: bold;
    color: #333;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
}

.product-desc {
    margin: 0 0 8px 0;
    font-size: 14px;
    color: #666;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 1.4;
}

.product-location-info {
    margin-top: 6px;
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.school-badge {
    background-color: #e6f7ff;
    border-radius: 4px;
    padding: 2px 8px;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    color: #4080ff;
    max-width: fit-content;
}

.school-badge i {
    color: #4080ff;
    font-size: 14px;
}

.location {
    margin: 0;
    font-size: 13px;
    color: #666;
    display: flex;
    align-items: center;
    gap: 4px;
}

.view-location-btn {
    background: none;
    border: none;
    font-size: 13px;
    color: #4080ff;
    padding: 0;
    margin-left: 8px;
    cursor: pointer;
    transition: all 0.2s;
}

.view-location-btn:hover {
    color: #3070e0;
    text-decoration: underline;
}

.product-right {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 16px;
    min-width: 100px;
}

.product-price {
    font-size: 18px;
    color: #333;
    font-weight: bold;
}

.item-actions {
    display: flex;
    justify-content: flex-end;
    padding: 8px 0 0;
}

.delete-btn {
    background: none;
    border: none;
    color: #999;
    cursor: pointer;
    font-size: 13px;
    padding: 6px 12px;
    display: flex;
    align-items: center;
    gap: 4px;
    transition: all 0.2s;
    border-radius: 4px;
}

.delete-btn:hover {
    color: #f56c6c;
    background-color: rgba(245, 108, 108, 0.1);
}

.quantity-control {
    display: flex;
    align-items: center;
    border: 1px solid #dcdfe6;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    transition: all 0.3s;
}

.cart-item:hover .quantity-control {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.quantity-btn {
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: none;
    border: none;
    cursor: pointer;
    color: #333;
    font-size: 14px;
    padding: 0;
    transition: all 0.2s;
}

.quantity-btn:hover:not(.disabled) {
    background-color: #f5f5f5;
}

.quantity-btn.minus {
    border-right: 1px solid #dcdfe6;
}

.quantity-btn.plus {
    border-left: 1px solid #dcdfe6;
}

.quantity-btn.disabled {
    color: #c0c4cc;
    cursor: not-allowed;
}

.quantity-value {
    text-align: center;
    width: 40px;
    font-size: 14px;
    color: #333;
    font-weight: bold;
}

.divider {
    height: 1px;
    background-color: #f0f0f0;
    margin: 0;
}

.item-divider {
    height: 1px;
    background-color: #eaeaea;
    margin: 16px 0 0 0;
}

.seller-divider {
    height: 16px;
    background-color: #f5f5f5;
    margin: 0;
}

.cart-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 16px;
    margin-top: 24px;
    position: sticky;
    bottom: 0;
    background-color: #fff;
    border-top: 1px solid #eaeaea;
    border-radius: 0 0 8px 8px;
    box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.05);
}

.footer-left {
    display: flex;
    align-items: center;
    gap: 24px;
}

.footer-right {
    display: flex;
    align-items: center;
    gap: 24px;
}

.text-btn {
    background: none;
    border: none;
    color: #666;
    cursor: pointer;
    font-size: 14px;
    padding: 6px 12px;
    transition: all 0.2s;
    border-radius: 4px;
}

.text-btn:hover {
    color: #f56c6c;
    background-color: rgba(245, 108, 108, 0.1);
}

.total {
    font-size: 16px;
    color: #333;
}

.total-price {
    font-size: 24px;
    font-weight: bold;
    color: #f56c6c;
    transition: all 0.3s;
}

.selected-count {
    font-size: 14px;
    color: #666;
}

.selected-count span {
    color: #f56c6c;
    font-weight: bold;
}

.checkout-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    width: 180px;
    height: 48px;
    font-size: 16px;
    background-color: #4080ff;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
    position: relative;
    overflow: hidden;
}

.checkout-btn:hover:not(.disabled) {
    background-color: #3070e0;
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(64, 128, 255, 0.25);
}

.checkout-btn:active:not(.disabled) {
    transform: translateY(0);
    box-shadow: 0 2px 8px rgba(64, 128, 255, 0.25);
}

.checkout-btn.disabled {
    background-color: #a0bfff;
    cursor: not-allowed;
}

.btn-text {
    position: relative;
    z-index: 2;
    transition: all 0.3s;
}

.btn-icon {
    position: relative;
    z-index: 2;
    font-size: 18px;
    transition: all 0.3s;
}

.checkout-btn:hover:not(.disabled) .btn-icon {
    transform: translateX(4px);
}

.checkout-btn::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: left 0.6s;
}

.checkout-btn:hover:not(.disabled)::before {
    left: 100%;
}

/* 动画效果 */
.item-fade-enter-active,
.item-fade-leave-active {
  transition: all 0.5s ease;
}
.item-fade-enter-from,
.item-fade-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

@media (max-width: 768px) {
    .cart-content-wrap {
        padding: 16px 12px;
        border-radius: 0;
    }
    
    .cart-item-content {
        flex-wrap: wrap;
    }
    
    .product-right {
        flex-direction: row;
        justify-content: space-between;
        width: 100%;
        margin-top: 12px;
        margin-left: 36px;
    }
    
    .footer-left, .footer-right {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }
    
    .cart-footer {
        flex-direction: column;
        align-items: stretch;
        gap: 20px;
    }
    
    .checkout-btn {
        width: 100%;
    }
}
</style>